package com.live.task;

import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.live.activity.LiveDetailActivity;
import com.live.activity.R;
import com.live.tools.LiveTools;

public class LiveMatch extends AsyncTask<String, Integer, String> {
	private List<Map<String, Object>> liveMatchList = new ArrayList<Map<String, Object>>();

	private ListView matchList = null;

	private Context context = null;

	private String today = null;

	public LiveMatch(Context context, ListView matchList, String today) {
		this.today = today;
		this.context = context;
		this.matchList = matchList;

	}

	ProgressDialog mProgressDialog = null;

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		Log.i("PageTask", "onPreExecute()  " + Thread.currentThread().getId());
		this.mProgressDialog = new ProgressDialog(context);
		this.mProgressDialog.setMessage("数据加载中，请稍候。");
		this.mProgressDialog.show();
	}

	@Override
	protected String doInBackground(String... params) {

		Log.i("PageTask", "doInBackground... " + Thread.currentThread().getId());
		liveMatchList = getServerData(params[0]);
		publishProgress(new Integer[0]);
		return null;
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		Log.i("PageTask", "onProgressUpdate()  " + Thread.currentThread().getId());

		SimpleAdapter adapter = new SimpleAdapter(context, liveMatchList, R.layout.match_list, new String[] {
				"matchName", "matchTime", "homeTeam", "homeTeamScore", "visitTeam", "visitTeamScore", "matchStatus",
				"matchRecord" }, new int[] { R.id.matchName, R.id.matchTime, R.id.homeTeam, R.id.homeTeamScore,
				R.id.visitTeam, R.id.visitTeamScore, R.id.matchStatus, R.id.matchRecord });

		matchList.setAdapter(adapter);
		matchList.setOnItemClickListener(new OnItemClickListener() {

			// 从当前画面到比分明细画面跳转，并传值。
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

				Map<String, Object> sportsMatch = liveMatchList.get(arg2);

				Intent intent = new Intent();

				intent.setClass(context, LiveDetailActivity.class);

				// 实例化 Bundle，设置需要传递的参数
				Bundle bundle = new Bundle();
				bundle.putString("matchId", sportsMatch.get("matchId").toString());
				bundle.putString("matchOptaId", sportsMatch.get("matchOptaId").toString());
				bundle.putString("matchName", sportsMatch.get("matchName").toString());
				bundle.putString("matchCategory", sportsMatch.get("matchCategory").toString());
				bundle.putString("matchTime", today + " " + sportsMatch.get("matchTime").toString());
				bundle.putString("homeTeam", sportsMatch.get("homeTeam").toString());
				bundle.putString("homeTeamScore", sportsMatch.get("homeTeamScore").toString());
				bundle.putString("homeTeamPic", sportsMatch.get("homeTeamPic").toString());
				bundle.putString("visitTeam", sportsMatch.get("visitTeam").toString());
				bundle.putString("visitTeamScore", sportsMatch.get("visitTeamScore").toString());
				bundle.putString("visitTeamPic", sportsMatch.get("visitTeamPic").toString());
				bundle.putString("matchStatus", sportsMatch.get("matchStatus").toString());

				intent.putExtras(bundle);

				context.startActivity(intent);
			}
		});
	}

	@Override
	protected void onPostExecute(String result) {
		Log.i("PageTask", "onPostExecute()  " + Thread.currentThread().getId());
		this.mProgressDialog.dismiss();
	}

	public List<Map<String, Object>> getServerData(String url) {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		HttpClient client = new DefaultHttpClient();
		try {
			HttpGet request = new HttpGet(new URI(url));
			request.addHeader("Accept-Encoding", "gzip");
			HttpResponse response = client.execute(request);

			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();

				if (entity != null) {
					String out = null;
					InputStream is = entity.getContent();
					if (entity.getContentEncoding().getValue().contains("gzip")) {
						out = LiveTools.isToString(is);
					} else {
						out = EntityUtils.toString(entity);
					}
					try {
						JSONArray matches = new JSONObject(out).getJSONArray("results");
						for (int i = 0; i < matches.length(); i++) {
							Map<String, Object> map = new HashMap<String, Object>();
							String matchTime = (String) matches.getJSONObject(i).get("matchTime");
							map.put("matchId", matches.getJSONObject(i).get("matchId"));
							map.put("matchOptaId", matches.getJSONObject(i).get("matchOptaId"));
							map.put("matchName", matches.getJSONObject(i).get("matchName"));
							map.put("matchCategory", matches.getJSONObject(i).get("matchCategory"));
							map.put("matchTime", matchTime.substring(11, 16));
							map.put("matchTimeAll", matchTime);
							map.put("homeTeam", matches.getJSONObject(i).get("homeTeam").toString().replace("?", "·"));
							map.put("homeTeamScore", matches.getJSONObject(i).get("homeTeamScore"));
							map.put("homeTeamPic", matches.getJSONObject(i).get("homeTeamPic"));
							map.put("visitTeam", matches.getJSONObject(i).get("visitTeam").toString().replace("?", "·"));
							map.put("visitTeamScore", matches.getJSONObject(i).get("visitTeamScore"));
							map.put("visitTeamPic", matches.getJSONObject(i).get("visitTeamPic"));
							map.put("matchStatus", matches.getJSONObject(i).get("matchStatus"));
							if ("实录".equals(matches.getJSONObject(i).get("matchRecord").toString())
									|| "直播间".equals(matches.getJSONObject(i).get("matchRecord").toString())) {
								map.put("matchRecord", "●");
							}
							data.add(map);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			Toast.makeText(context, "远程服务器无响应，请稍候再试！", Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
		return data;
	}
}